package com.hunter.apps;

import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

import org.apache.lucene.search.Query;

import com.hunter.lucene.util.config.Configuration;
import com.hunter.lucene.util.search.QuerySession;
import com.hunter.lucene.util.search.Searchable;
import com.hunter.util.LogUtil;
import com.hunter.util.ConfigManager;
import com.hunter.util.PropertiesUtil;
import com.hunter.util.QueryManager;
import com.hunter.util.SystemUtil;
import com.hunter.view.MainFrame;
import com.hunter.view.StartWindow;
import com.mkk.swing.SwingUtil;
import com.mkk.swing.SwingUtil.UIType;

/**
 * 2010-8-10 下午09:18:36<br>
 * 程序主启动类
 * 
 * @author mkk
 */
public class Apps {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// set UI
		SwingUtil.setUI(UIType.WINDOWS);
		// start
		SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() {
			// start window
			private StartWindow win = new StartWindow();
			private JProgressBar bar = win.getProgressBar1();

			protected Void doInBackground() throws Exception {
				win.setVisiable(true);
				bar.setVisible(true);
				// config object
				Configuration config = Configuration
						.build(PropertiesUtil.CONFIG_FILE);

				// 判断是否有索引文件
				if (SystemUtil.isIndexFileExist()) {
					QuerySession querySession = null;
					try {
						// 有则创建对应的缓存对象
						bar.setValue(10);
						Searchable searcher = config.getOrBuildSearcher();
						bar.setValue(40);
						Query query = QueryManager.getQueryManager()
								.getDefaultQuery("abcd");
						bar.setValue(60);
						querySession = searcher.createQuerySession(query);
						bar.setValue(80);
						querySession.execute();

					} catch (Exception e) {
						e.printStackTrace();
						LogUtil.saveExceptionLog(e);
					} finally {
						// last
						bar.setValue(bar.getMaximum());
						if (querySession != null) {
							querySession.close();
						}
					}
				} else {
					// 没有则显示下启动界面,等待半秒
					try {
						bar.setValue(40);
						Thread.sleep(500);
					} catch (InterruptedException ex) {
					}
				}
				// save
				ConfigManager.getManager().setConfig(config);
				return null;
			}

			protected void done() {
				win.setVisiable(false);
				// show mainFrame
				new MainFrame();
			}

		};
		worker.execute();

	}

}
